<?php

namespace Biz\model\brand;

use Doraemon\pockets\datebase\BaseDbModel;

/**
 * 品牌订单
 *
 * @category   Module name
 * @package    PSR
 * @subpackage Documentation\API
 * @author     zhouyang  <zhouyang@haohaozhu.com>
 * @license    GPL http://www.haohaozhu.com
 * @link       http://www.haohaozhu.com
 */
class BrandOrder extends BaseDbModel
{
    const _CONFIG_FILE_ = 'db_store';

    const _CONFIG_SELECT_ = 'db_store';

    const _DATABASE_ = 'store';

    const _TABLE_NAME = 'brand_order';

    const _SUB_TABLE = false;

    // 创建订单
    const ORDER_STATUS_CREATE = 1;
    // 完成订单
    const ORDER_STATUS_FINISHED = 2;
    // 取消订单
    const ORDER_STATUS_CANCEL = 3;
    // 系统取消订单
    const ORDER_STATUS_SYS_CANCEL = 4;

    // 未支付
    const PAY_STATUS_UNPAID = 1;
    // 已支付
    const PAY_STATUS_PAID = 2;
    // 支付失败
    const PAY_STATUS_FAIL = 3;

    // 支付平台（1：支付宝；2：微信；3：银行转账）
    const PAY_PLATFORM_ALI_PAY = 1;
    const PAY_PLATFORM_WE_CHAT = 2;
    const PAY_PLATFORM_BANK = 3;

    const PAY_PLATFORM = [
        '' => '全部',
        BrandOrder::PAY_PLATFORM_ALI_PAY => '支付宝',
        BrandOrder::PAY_PLATFORM_WE_CHAT => '微信',
        BrandOrder::PAY_PLATFORM_BANK => '银行转账'
    ];

    // 订单服务状态
    const SERVICE_STATUS_FINISHED = 1;
    const SERVICE_STATUS_UNFINISHED = 0;
    const SERVICE_STATUS_MAP = [
        self::SERVICE_STATUS_FINISHED => '已完成',
        self::SERVICE_STATUS_UNFINISHED => '未完成'
    ];

    //订单类型
    const ORDER_TYPE_NEW = 1;//新签
    const ORDER_TYPE_UPGRADE = 2;//升级
    const ORDER_TYPE_RENEW = 3;//续费
    const ORDER_TYPE_MAP = [
        self::ORDER_TYPE_NEW => '新签',
        self::ORDER_TYPE_UPGRADE => '升级',
        self::ORDER_TYPE_RENEW => '续费'
    ];


    /**
     * 创建订单
     * @param $orderType
     * @param $brand_sn
     * @param $uid
     * @param $brand_id
     * @param $brand_name
     * @param $package_id
     * @param $package_name
     * @param $pay_platform
     * @param $price
     * @param $product_price
     * @param $pack_type
     * @param $inStartTime
     * @param $inEndTime
     * @param $remark
     * @param $adminId
     * @return int
     */
    public static function createOrder(
        $orderType,
        $brand_sn,
        $uid,
        $brand_id,
        $brand_name,
        $package_id,
        $package_name,
        $pay_platform,
        $price,
        $product_price,
        $pack_type,
        $inStartTime,
        $inEndTime,
        $remark,
        $adminId
    )
    {
        $data = [
            'dsn' => $brand_sn,
            'uid' => $uid,
            'brand_id' => $brand_id,
            'brand_name' => $brand_name,
            'package_id' => $package_id,
            'package_name' => $package_name,
            'identify' => $package_name,
            'pay_platform' => $pay_platform,
            'price' => $price,
            'product_price' => $product_price,
            'add_time' => time(),
            'pack_type' => $pack_type,
            'in_start_time' => $inStartTime,
            'in_end_time' => $inEndTime,
            'remark' => $remark,
            'admin_id' => $adminId,
            'order_type' => $orderType
        ];

        return self::insert($data)->rowCount();
    }

    /**
     * 查询订单信息
     * @param $order_sn
     * @return array|mixed
     */
    public static function getOrder($order_sn)
    {
        return self::get('*', ['dsn' => $order_sn]);
    }

    /**
     * 更新支付状态
     * @param $order_sn
     * @param $other_sn
     * @param $pay_status
     * @param $pay_time
     * @param $pay_platform
     * @param $amount
     * @param int $order_status
     * @param int $service_status
     * @return bool|int
     */
    public static function updatePayStatus(
        $order_sn,
        $other_sn,
        $pay_status,
        $pay_time,
        $pay_platform,
        $amount,
        $order_status,
        $service_status
    )
    {
        if ($pay_status == self::PAY_STATUS_FAIL || $pay_status == self::PAY_STATUS_PAID) {
            $data = [
                'other_sn' => $other_sn,
                'pay_platform' => $pay_platform,
                'amount' => $amount,
                'pay_time' => $pay_time,
                'pay_status' => $pay_status,
                'order_status' => $order_status,
                'service_status' => $service_status
            ];
            return self::update($data, ['dsn' => $order_sn])->rowCount();
        }
        return false;
    }

    /**
     * 检查是否当前商品和支付平台在当天有过未支付订单
     * @param $uid
     * @param $package_id
     * @param $pay_platform
     * @return array|mixed
     */
    public static function findTodayOrderByUid($uid, $package_id, $pay_platform)
    {
        $start_time = strtotime(date('Y-m-d'));
        $end_time = strtotime(date('Y-m-d 23:59:59'));

        return self::get('*', [
            'uid' => $uid,
            'package_id' => $package_id,
            'pay_platform' => $pay_platform,
            'order_status' => self::ORDER_STATUS_CREATE,
            'pay_status' => self::PAY_STATUS_UNPAID,
            'add_time[<>]' => [$start_time, $end_time],
        ]);
    }

    /**
     * @param $uid
     * @return array|mixed
     */
    public static function findAllPaidOrder($uid)
    {
        $start_time = strtotime(date('Y-m-d')) - 365 * 3600 * 24;
        $end_time = strtotime(date('Y-m-d 23:59:59'));
        return self::get('*', [
            'uid' => $uid,
            'order_status' => self::ORDER_STATUS_FINISHED,
            'pay_status' => self::PAY_STATUS_PAID,
            'add_time[<>]' => [$start_time, $end_time],
        ]);
    }

    public static function hasOrder($brandId, $where = [])
    {
        $where = array_merge($where, [
            'brand_id' => $brandId,
            'order_status' => self::ORDER_STATUS_FINISHED,
            'pay_status' => self::PAY_STATUS_PAID,
        ]);
        $info = self::get('*', $where);
        return !empty($info) ? true : false;
    }

    public static function hasUsedOrder($uids)
    {
        $uids = is_array($uids) ? $uids : [$uids];
        $list = BrandOrder::select('*', [
                'order_status' => self::ORDER_STATUS_FINISHED,
                'pay_status' => self::PAY_STATUS_PAID,
                'uid' => $uids,
                'in_end_time[>]' => date('Y-m-d')
            ]
        );
        $list = array_column($list, null, 'uid');
        $result = [];
        foreach ($uids as $uid) {
            $result[$uid] = isset($list[$uid]) ? 1 : 0;
        }
        return $result;
    }

    public static function getUnUsedOrder($uid)
    {
        $info = BrandOrder::get('*', [
                'order_status' => self::ORDER_STATUS_FINISHED,
                'pay_status' => self::PAY_STATUS_PAID,
                'uid' => $uid,
                'in_start_time[>]' => date('Y-m-d')
            ]
        );
        return $info;
    }

    /**
     * 查询用户是否存在未生效的订单(续费订单，未到期生效)
     * @param $uids
     * @return array
     */
    public static function hasUnUsedOrder($uids)
    {
        $uids = is_array($uids) ? $uids : [$uids];
        $list = BrandOrder::select('*', [
                'order_status' => self::ORDER_STATUS_FINISHED,
                'pay_status' => self::PAY_STATUS_PAID,
                'uid' => $uids,
                'in_start_time[>]' => date('Y-m-d')
            ]
        );
        $list = array_column($list, null, 'uid');
        $result = [];
        foreach ($uids as $uid) {
            $result[$uid] = isset($list[$uid]) ? 1 : 0;
        }
        return $result;
    }

    /**
     * 获取今天需要入驻的品牌订单(延时订单)
     * @return array|bool
     */
    public static function getTodayInOrder()
    {
        $start = date('Y-m-d');
        $end = date('Y-m-d', strtotime('+1 day'));
        //debug
//        $start = '2022-04-30';
//        $end = date('Y-m-d', strtotime('+1 day', strtotime($start)));
        $where = [
            'in_start_time[>=]' => $start,
            'in_start_time[<]' => $end,
            'order_status' => self::ORDER_STATUS_FINISHED,
            'pay_status' => self::PAY_STATUS_PAID,
            'service_status' => self::SERVICE_STATUS_UNFINISHED
        ];
        $list = self::select('*', $where);
        return $list;
    }

    public static function insertData($data)
    {
        self::insert($data);
        return self::id();
    }
}
